#!/usr/bin/env  python
#coding=utf-8

import os
import time
import sys
from ftplib import FTP
from  pyinotify import  WatchManager, Notifier, ProcessEvent, IN_DELETE, IN_CREATE,IN_MOVED_TO,IN_MOVED_FROM,IN_CLOSE_WRITE

class MonitorFile(ProcessEvent):                                          
    def process_IN_CLOSE_WRITE(self, event):
        file = os.path.join(event.path, event.name)
        ftp_up(file)


    def process_IN_DELETE(self, event):
        file = os.path.join(event.path, event.name)
        ftp_del(file)


#文件上传 
def ftp_up(filename): 
    ftp=FTP()
    ftp.set_debuglevel(0)      #调试级别2，显示详细信息;0为关闭调试信息 
    ftp.connect('ftp_ip','21') #连接 
    ftp.login('user','passwd')  #登录，如果匿名登录则用空串代替即可 
    dir = filename.split('/')
    if 'upload_images' in dir:
        ftp.cwd('impkg/images/') #选择操作目录    
        try:
            ftp.mkd(dir[-2])
        except:
            pass
        ftp.cwd('impkg/images/%s' %dir[-2])
        bufsize = 1024       #设置缓冲块大小 
        file_handler = open(filename,'rb')  #以读模式在本地打开文件 
        ftp.storbinary('STOR %s' % os.path.basename(filename),file_handler,bufsize) #上传文件 
        file_handler.close() 
        ftp.quit()
        print "ftp_up %s in %s done..." %(os.path.basename(filename),os.path.dirname(filename))
    elif 'upload_sdk' in dir:
        ftp.cwd('impkg/sdk_pkg/') #选择操作目录 
        try: #创建新的目录 目录名称以日期创建
            ftp.mkd(dir[-2])
        except:
            pass
        ftp.cwd('impkg/sdk_pkg/%s' %dir[-2])
        bufsize = 1024
        file_handler = open(filename,'rb')
        ftp.storbinary('STOR %s' % os.path.basename(filename),file_handler,bufsize) #上传文件 
        file_handler.close()
        ftp.quit()
        print "ftp_up %s in %s done..." %(os.path.basename(filename),os.path.dirname(filename))
    else:
        pass

#文件删除
def ftp_del(filename):
    dir = filename.split('/') 
    ftp=FTP()
    ftp.set_debuglevel(0) 
    ftp.connect('ftp_ip','21') 
    ftp.login('user','passwd') 
    if 'upload_images' in dir:
        ftp.cwd('impkg/images/%s' %dir[-2])
        bufsize = 1024 
        ftp.delete('%s' %os.path.basename(filename))
        ftp.quit()
    elif 'upload_sdk' in dir:
        ftp.cwd('impkg/sdk_pkg/%s' %dir[-2])
        bufsize = 1024 
        ftp.delete('%s' %os.path.basename(filename))
        file_handler.close()
        ftp.quit()
    else:
        pass


path = "/data/upload_images/"
wm = WatchManager() 
mask = IN_DELETE|IN_CLOSE_WRITE
notifier = Notifier(wm, MonitorFile ())
wm.add_watch(path, mask,rec=True)
  

if __name__ == "__main__":
    while True:
        try :
            notifier.process_events()
            if notifier.check_events():
                notifier.read_events()
        except KeyboardInterrupt:
            notifier.stop()
            break